<?php
require_once(SITE_ROOT . 'class/db/DB.class.php');
require_once(SITE_ROOT . 'class/bean/Division.class.php');

class DBDivision {
	
	public function getDivisions() {
		$db = new DB();
		$connection = $db->connect();
		
		if ($stmt = $connection->prepare('SELECT DISTINCT `division#`, `size`, `closed` FROM `tdivision`')) {
			$stmt->execute();
			$stmt->bindColumn(1, $divisionID, PDO::PARAM_INT);
			$stmt->bindColumn(2, $size, PDO::PARAM_INT);
			$stmt->bindColumn(3, $closed, PDO::PARAM_BOOL);
			
			$divisions = new ArrayObject();
			
			while ($stmt->fetch()) {
				$division = new Division();
				$division->setDivisionID($divisionID);
				$division->setSize($size);
				$division->setClosed($closed);
				$divisions->append($division);
			}
			return $divisions;
		}
	}
	
	public function getDivisionsByCountry($country, $includingClosed = null) {
		$db = new DB();
		$connection = $db->connect();
		
		if ($includingClosed == null || $includingClosed == false) {
			$statement = 'SELECT `division#`, `size`, `closed` FROM `tdivision` WHERE `country#` = ? AND `closed` = ?';
		}
		else $statement = 'SELECT `division#`, `size`, `closed` FROM `tdivision` WHERE `country#` = ?'; 
		
		if ($stmt = $connection->prepare($statement)) {
			if ($includingClosed == null || $includingClosed == false) {
				$stmt->execute(array($country->getCountryID(), false));
			}
			else $stmt->execute(array($country->getCountryID()));
						
			$stmt->bindColumn(1, $divisionID, PDO::PARAM_INT);
			$stmt->bindColumn(2, $size, PDO::PARAM_INT);
			$stmt->bindColumn(3, $closed, PDO::PARAM_BOOL);
			
			$divisions = new ArrayObject();
			
			while ($stmt->fetch()) {
				$division = new Division();
				$division->setDivisionID($divisionID);
				$division->setSize($size);
				$division->setClosed($closed);
				$division->setCountry($country);
				$divisions->append($division);
			}
			return $divisions;
		}
	}
	
	public function saveDivisions($divisions) {
		$db = new DB();
		$connection = $db->connect();
		
		if ($stmt = $connection->prepare('INSERT INTO `tdivision` (`country#`, `division#`, `size`, `closed`) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE `size`=VALUES(`size`), `closed`=VALUES(`closed`)')) {
			foreach ($divisions as $division) {
				$countryID = $division->getCountry()->getCountryID();
				$divisionID = $division->getDivisionID();
				$size = $division->getSize();
				$closed = $division->isClosed();
				
				$stmt->execute(array($countryID, $divisionID, $size, $closed));
			}
		}
	}
	
	public function deleteDivisionsByCountry($country) {
		$db = new DB();
		$connection = $db->connect();
		
		if ($stmt = $connection->prepare('DELETE FROM `tdivision` WHERE `country#` = ?')) {
			$stmt->execute(array($country->getCountryID()));
		}
	}
	
}

?>